<template>
  <div class="upload-container">
    <div v-for="(item, index) in value" :key="index" class="images">
      <el-image
        v-if="index < max"
        :src="item"
        :style="`width:${width}px;height:${height}px;`"
        fit="cover"
      />
      <div class="mask">
        <div class="actions">
          <span title="预览" @click="preview(index)">
            <i class="el-icon-zoom-in" />
          </span>
          <span title="移除" @click="remove(index)">
            <i class="el-icon-delete" />
          </span>
          <span
            v-show="value.length > 1"
            title="左移"
            :class="{ disabled: index == 0 }"
            @click="move(index, 'left')"
          >
            <i class="el-icon-back" />
          </span>
          <span
            v-show="value.length > 1"
            title="右移"
            :class="{ disabled: index == value.length - 1 }"
            @click="move(index, 'right')"
          >
            <i class="el-icon-right" />
          </span>
        </div>
      </div>
    </div>
    <el-upload
      v-show="!Array.isArray(value) || value.length < max"
      v-loading="isLoading"
      :show-file-list="false"
      :headers="headers"
      action="/"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
      :on-success="handleSuccess"
      drag
      class="images-upload"
    >
      <div class="image-slot" :style="`width:${width}px;height:${height}px;`">
        <i class="el-icon-plus" />
      </div>
    </el-upload>
    <div v-if="!notip" class="el-upload__tip">
      <div style="display: inline-block;">
        <span slot="title">
          {{
            uploadTips
              ? uploadTips
              : `上传图片支持 ${uploadType.join(
                ' / '
              )} 格式，且图片大小不超过 ${size /
                1024}MB，且图片数量不超过 ${max} 张`
          }}</span>
      </div>
    </div>
    <el-image-viewer
      v-if="imageViewerVisible"
      :on-close="closePreview"
      :url-list="value"
      :initial-index="imageViewerIndex"
    />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import ImgUploadMixin from '../mixins/ImgUploadFn'
import { upload } from 'dependencies/api/index'
import SectionLoadingMixin from 'modules/mixins/section-loading'

let prevOverflow = ''
export default {
  name: 'ImagesUpload',
  components: {
    ElImageViewer
  },
  mixins: [ImgUploadMixin, SectionLoadingMixin],
  props: {
    headers: {
      type: Object,
      default: () => {}
    },
    value: {
      type: Array
    },
    max: {
      type: Number,
      default: 3
    },
    placeholder: {
      type: String,
      default: ''
    },
    notip: {
      type: Boolean,
      default: false
    },
    imgWidth: {
      type: Number,
      default: 150
    },
    imgHeight: {
      type: Number,
      default: 150
    },
    uploadType: {
      type: Array,
      default: () => ['jpg', 'jpeg', 'png', 'gif']
    }
  },
  data() {
    return {
      imageViewerIndex: 0,
      imageViewerVisible: false
    }
  },
  computed: {
    width() {
      return this.imgWidth || this.uploadWidth
    },
    height() {
      return this.imgHeight || this.uploadHeight
    }
  },
  methods: {
    // 预览
    preview(index) {
      this.imageViewerIndex = index
      // prevent body scroll
      prevOverflow = document.body.style.overflow
      document.body.style.overflow = 'hidden'
      this.imageViewerVisible = true
    },
    closePreview() {
      document.body.style.overflow = prevOverflow
      this.imageViewerVisible = false
    },
    // 移除
    remove(index) {
      const value = this.value
      value.splice(index, 1)
    },
    // 移动
    move(index, type) {
      const value = this.value
      if (type === 'left' && index !== 0) {
        value[index] = value.splice(index - 1, 1, value[index])[0]
      }
      if (type === 'right' && index !== value.length - 1) {
        value[index] = value.splice(index + 1, 1, value[index])[0]
      }
    },
    async beforeUpload(file) {
      let errorMsg = ''
      const typeLimit = this.typeLimit(file)
      if (typeLimit) {
        this.$message.error(typeLimit)
        return Promise.reject()
      }

      const sizeLimit = this.sizeLimit(file)
      sizeLimit && (errorMsg += sizeLimit)
      const widthHeightLimit = await this.widthHeightLimit(file)
      widthHeightLimit && (errorMsg += widthHeightLimit)
      // 自定义事件一定要在获取宽高之后
      const validateMsg = this.customLimit(file)
      validateMsg && (errorMsg += validateMsg)

      if (errorMsg) {
        this.$message.error(errorMsg)
        return Promise.reject()
      }
      return true
    },
    handleSuccess(res, file, fileList) {
      if (res.success && res.data) {
        this.$message.success('上传成功!')
        if (Array.isArray(this.value)) {
          this.value.push(res.data)
        } else {
          this.$emit('input', [res.data])
        }
      }
    },
    async httpRequest(data) {
      this.loading()
      const file = new FormData()
      file.append('file', data.file)
      try {
        const res = await upload(file)

        if (res.success) {
          return res
        } else {
          this.handleError()
        }
      } finally {
        this.loaded()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-container {
  line-height: initial;
}
.images {
  position: relative;
  display: inline-block;
  margin-right: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  .el-image {
    display: block;
  }
  .mask {
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    font-size: 24px;
    background-color: rgba(0, 0, 0, 0.5);
    transition: all 0.3s;
    .actions {
      width: 100px;
      height: 100px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: center;
      left: 50%;
      top: 50%;
      position: absolute;
      transform: translateX(-50%) translateY(-50%);
      span {
        width: 50%;
        text-align: center;
        color: #fff;
        cursor: pointer;
        transition: all 0.1s;
        &.disabled {
          color: #999;
          cursor: not-allowed;
        }
        &:hover:not(.disabled) {
          transform: scale(1.5);
        }
      }
    }
  }
  &:hover .mask {
    opacity: 1;
  }
}
.images-upload {
  display: inline-block;
}
::v-deep .el-upload {
  .el-upload-dragger {
    width: auto;
    height: auto;
    &.is-dragover {
      border-width: 1px;
    }
    .image-slot {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      color: #909399;
      font-size: 30px;
      background-color: transparent;
    }
    .progress {
      position: absolute;
      top: 0;
      &::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        background-color: rgba(0, 0, 0, 0.2);
      }
      .el-progress {
        z-index: 1;
        left: 50%;
        top: 50%;
        position: absolute;
        transform: translateX(-50%) translateY(-50%);
        .el-progress__text {
          color: #fff;
        }
      }
    }
  }
}
</style>
